package org.example.school.business;

import lombok.Getter;
import lombok.Setter;
import org.example.school.common.Context;
import org.example.school.entity.*;
import org.example.school.model.dto.ChatMessageDTO;
import org.example.school.model.dto.GuardianProfileDTO;
import org.example.school.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class ChatInfo {

    @Autowired
    private IStudentsService studentsService;

    @Autowired
    private IClassesService classesService;

    @Autowired
    private ITeachersService teachersService;

    @Autowired
    private IParentsService parentsService;

    @Autowired
    private IUsersService usersService;
    
    @Autowired
    private IMessagesService messagesService;

    @Autowired
    private IStudentParentRelationsService studentParentRelationsService;
    @Autowired
    private ITeacherClassRelationsService teacherClassRelationsService;
    @Autowired
    private ISubjectsService subjectsService;


    /**
     * 获取监护人的联系人列表
     * @param studentNumber 学生学号
     * @return 老师联系人列表
     */
    public List<ContactInfo> getParentContacts(String studentNumber) {
        Long userId = Context.getId();
        Users currentUser = usersService.getById(userId);
        if (!"3".equals(currentUser.getUserType())) { // 不是家长
            throw new RuntimeException("您没有权限查看老师联系人");
        }

        // 获取监护人信息
        GuardianProfileDTO parentProfile = parentsService.getGuardianProfile(userId);
        List<ContactInfo> contacts = new ArrayList<>();

        // 获取指定孩子所在班级的班主任
        for (GuardianProfileDTO.ChildInfo child : parentProfile.getChildren()) {
            // 只处理指定学号的孩子
            if (!child.getStudentNumber().equals(studentNumber)) {
                continue;
            }
            
            Students student = studentsService.lambdaQuery()
                    .eq(Students::getStudentNumber, child.getStudentNumber())
                    .one();

            if (student != null) {
                // 获取班级信息
                Classes clazz = classesService.getById(student.getClassId());
                if (clazz != null) {
                    // 获取班主任信息
                    Teachers teacher = teachersService.getById(clazz.getHeadTeacherId());
                    List<TeacherClassRelations> teacherClassRelations = teacherClassRelationsService.lambdaQuery()
                            .eq(TeacherClassRelations::getClassId, clazz.getId())
                            .ne(TeacherClassRelations::getTeacherId, teacher.getId())
                            .list();
                    for ( TeacherClassRelations teacherClassRelation : teacherClassRelations){
                        Teachers teachersServiceById = teachersService.getById(teacherClassRelation.getTeacherId());
                        Subjects subjectsServiceById = subjectsService.getById(teacherClassRelation.getSubjectId());
                        ContactInfo contact = new ContactInfo();
                        contact.setUserId(teachersServiceById.getUserId());
                        contact.setFullName(teachersServiceById.getFullName());
                        contact.setUserType("1");
                        contact.setSubejt(subjectsServiceById.getName());
                        contacts.add(contact);
                    }

                    if (teacher != null) {
                        // 获取班主任对应的用户信息
                        Users teacherUser = usersService.lambdaQuery()
                                .eq(Users::getId, teacher.getUserId())
                                .one();

                        if (teacherUser != null) {
                            ContactInfo contact = new ContactInfo();
                            contact.setUserId(teacherUser.getId());
                            contact.setFullName(clazz.getClassName() + "老师 " + teacher.getFullName());
                            contact.setUserType("1"); // 老师
                            contacts.add(contact);
                        }
                    }
                }
            }
        }
        return contacts;
    }
    /**
     * 获取老师的联系人列表
     * @return 家长联系人列表
     */
    public List<ContactInfo> getTeacherContacts(Long classId, String studentName, String studentNumber) {
        Long userId = Context.getId();
        System.out.println("Current user ID from Context: " + userId);
        
        if (userId == null) {
            throw new RuntimeException("用户未登录或会话已过期");
        }
        
        Users currentUser = usersService.getById(userId);
        System.out.println("Current user from database: " + currentUser);
        
        if (currentUser == null) {
            throw new RuntimeException("用户不存在");
        }
        
        if (!"1".equals(String.valueOf(currentUser.getUserType()))) { // 不是老师
            throw new RuntimeException("您没有权限查看家长联系人");
        }

        // 获取老师信息
        Teachers teacher = teachersService.lambdaQuery()
                .eq(Teachers::getUserId, userId)
                .one();
        if (teacher == null) {
            throw new RuntimeException("教师信息不存在");
        }

        // 获取班级信息
        Classes clazz = classesService.getById(classId);
        if (clazz == null) {
            throw new RuntimeException("班级信息不存在");
        }

        // 验证该老师是否是该班级的班主任
        if (!clazz.getHeadTeacherId().equals(teacher.getId())) {
            throw new RuntimeException("您不是该班级的班主任");
        }
        List<TeacherClassRelations> teacherClassRelations = teacherClassRelationsService.lambdaQuery()
                .eq(TeacherClassRelations::getClassId, classId)
                .ne(TeacherClassRelations::getTeacherId, teacher.getId())
                .list();

        List<ContactInfo> contacts = new ArrayList<>();
        // 获取该班级的所有学生
        List<Students> students = studentsService.lambdaQuery()
                .eq(Students::getClassId, classId)
                .eq(StringUtils.hasText(studentNumber),Students::getStudentNumber, studentNumber)
                .like(StringUtils.hasText(studentName),Students::getFullName, studentName)
                .list();

        if (!StringUtils.isEmpty(studentNumber)||StringUtils.isEmpty(studentName)) {
            for (TeacherClassRelations teacherClassRelation : teacherClassRelations) {
                Teachers teachersServiceById = teachersService.getById(teacherClassRelation.getTeacherId());
                Subjects subjectsServiceById = subjectsService.getById(teacherClassRelation.getSubjectId());
                ContactInfo contact = new ContactInfo();
                contact.setUserId(teachersServiceById.getUserId());
                contact.setFullName(teachersServiceById.getFullName());
                contact.setUserType("1");
                contact.setSubejt(subjectsServiceById.getName());
                contacts.add(contact);
            }
        }

        for (Students student : students) {
            // 获取学生的家长信息
            List<StudentParentRelations> relations = studentParentRelationsService.lambdaQuery()
                    .eq(StudentParentRelations::getStudentId, student.getId())
                    .list();

            for (StudentParentRelations relation : relations) {
                Parents parent = parentsService.getById(relation.getParentId());
                if (parent != null) {
                    // 获取家长对应的用户信息
                    Users parentUser = usersService.lambdaQuery()
                            .eq(Users::getId, parent.getUserId())
                            .one();

                    if (parentUser != null) {
                        // 获取家长详细信息
                        GuardianProfileDTO guardianProfile = parentsService.getGuardianProfile(parent.getUserId());

                        ContactInfo contact = new ContactInfo();
                        contact.setUserId(parentUser.getId());
                        contact.setFullName(student.getFullName() + "家长 " + guardianProfile.getFullName());
                        contact.setUserType("3"); // 家长
                        contacts.add(contact);
                    }
                }
            }
        }

        return contacts;
    }
    
    /**
     * 发送消息
     * @param recipientId 接收方用户ID
     * @param content 消息内容
     * @return 发送结果
     */
    public ChatMessageDTO sendMessage(Long recipientId, String content) {
        Long senderId = Context.getId();
        
        // 验证接收方是否存在
        Users recipient = usersService.getById(recipientId);
        if (recipient == null) {
            throw new RuntimeException("接收方用户不存在");
        }

        // 创建消息
        Messages message = new Messages();
        message.setSenderId(senderId);
        message.setRecipientId(recipientId);
        message.setContent(content);
        message.setIsRead(false);
        message.setSentAt(LocalDateTime.now());
        message.setMessageType("text"); // 默认文本消息
        message.setStatus("sent"); // 已发送状态
        message.setUpdatedAt(LocalDateTime.now());
        
        // 保存消息
        messagesService.save(message);
        
        // 转换为DTO
        ChatMessageDTO messageDTO = new ChatMessageDTO();
        BeanUtils.copyProperties(message, messageDTO);
        
        // 设置发送方和接收方姓名
        Users sender = usersService.getById(senderId);
        messageDTO.setSenderName(getUserDisplayName(sender));
        messageDTO.setRecipientName(getUserDisplayName(recipient));
        
        return messageDTO;
    }
    
    /**
     * 获取聊天历史记录
     * @param contactId 联系人ID
     * @param page 页码
     * @param size 每页大小
     * @return 消息列表
     */
    public List<ChatMessageDTO> getChatHistory(Long contactId, int page, int size) {
        Long userId = Context.getId();
        
        // 验证联系人是否存在
        Users contact = usersService.getById(contactId);
        if (contact == null) {
            throw new RuntimeException("联系人不存在");
        }

        
        // 查询聊天记录（包括发送给对方的和对方发送给我的）
        List<Messages> messages = messagesService.lambdaQuery()
                .and(wrapper -> wrapper.eq(Messages::getSenderId, userId).eq(Messages::getRecipientId, contactId)
                        .or()
                        .eq(Messages::getSenderId, contactId).eq(Messages::getRecipientId, userId))
                .orderByAsc(Messages::getSentAt) // 按时间升序排列
                .last("LIMIT " + (page * size) + "," + size)
                .list();
        
        // 转换为DTO列表
        return messages.stream().map(message -> {
            ChatMessageDTO dto = new ChatMessageDTO();
            BeanUtils.copyProperties(message, dto);
            
            // 设置发送方和接收方姓名
            Users sender = usersService.getById(message.getSenderId());
            Users recipient = usersService.getById(message.getRecipientId());
            dto.setSenderName(getUserDisplayName(sender));
            dto.setRecipientName(getUserDisplayName(recipient));
            
            return dto;
        }).collect(Collectors.toList());
    }
    
    /**
     * 获取未读消息数
     * @return 未读消息数
     */
    public Long getUnreadCount() {
        Long userId = Context.getId();
        
        return messagesService.lambdaQuery()
                .eq(Messages::getRecipientId, userId)
                .eq(Messages::getIsRead, false)
                .count();
    }
    
    /**
     * 获取每个联系人的未读消息数
     * @param contactIds 联系人ID列表
     * @return 每个联系人的未读消息数映射
     */
    public Map<Long, Long> getUnreadCountByContacts(List<Long> contactIds) {
        Long userId = Context.getId();
        Map<Long, Long> unreadCounts = new HashMap<>();
        
        for (Long contactId : contactIds) {
            Long count = messagesService.lambdaQuery()
                    .eq(Messages::getSenderId, contactId)
                    .eq(Messages::getRecipientId, userId)
                    .eq(Messages::getIsRead, false)
                    .count();
            unreadCounts.put(contactId, count);
        }
        
        return unreadCounts;
    }
    
    /**
     * 标记消息为已读
     * @param senderId 发送方ID
     * @return 标记结果
     */
    public String markAsRead(Long senderId) {
        Long userId = Context.getId();
        
        // 将来自senderId且发送给当前用户的所有未读消息标记为已读
        messagesService.lambdaUpdate()
                .eq(Messages::getSenderId, senderId)
                .eq(Messages::getRecipientId, userId)
                .eq(Messages::getIsRead, false)
                .set(Messages::getIsRead, true)
                .set(Messages::getUpdatedAt, LocalDateTime.now())
                .set(Messages::getStatus, "read")
                .update();
        
        return "消息已标记为已读";
    }
    
    /**
     * 获取用户的显示名称
     * @param user 用户
     * @return 显示名称
     */
    private String getUserDisplayName(Users user) {
        if (user == null) {
            return "未知用户";
        }
        
        switch (user.getUserType()) {
            case "1": // 老师
                Teachers teacher = teachersService.lambdaQuery()
                        .eq(Teachers::getUserId, user.getId())
                        .one();
                return teacher != null ? teacher.getFullName() : user.getUsername();
                
            case "3": // 家长
                Parents parent = parentsService.lambdaQuery()
                        .eq(Parents::getUserId, user.getId())
                        .one();
                return parent != null ? parent.getFullName() : user.getUsername();
                
            default:
                return user.getUsername();
        }
    }


    /**
     * 联系人信息类
     */
    @Setter
    @Getter
    public static class ContactInfo {
        private Long userId;
        private String fullName;
        private String userType; // 1:老师, 2:学生, 3:家长
        private String subejt ;

    }
}